import { Table, Switch, Button, Select, TreeSelect, message, Modal, Spin, Empty, Affix } from 'antd';
import React, { useState, useEffect } from 'react';
import './index.scss'
import apis from './../../../../../apis'
import { http, udConfigProvider, uaaApp } from '@/lib';
import { TreeSelectInTable } from './TreeSelectInTable';
import { SelectInTable } from './SelectInTable';


const brandInformationEditAuth = 'user_customer_manager_brandInformation_edit' //维护品牌信息（管理区域、管理主考核客户）
const salesmanEditAuth = 'user_customer_manager_salesman_edit'//维护业务员

enum TableColumnFiledMap {
    //所属品牌
    brandName = "brandCode",
    //管理区域
    area = "belongAreaCode",
    //关联业务员
    connect = "salesmans",
    //是否支持一户多开
    isAble = "isAble",
    //关联主考核客户
    connectCustoemr = "partnerAgentCode",
    //状态
    status = "isValid",
    //盘点权限
    openCheckStock = 'openCheckStock',
    //配额权限
    openQuota='openQuota',
    //盘点编辑权限
    allowEditStock='allowEditStock'

}

const defaultTableDataItem = {
    [TableColumnFiledMap.brandName]: undefined,
    [TableColumnFiledMap.area]: undefined,
    [TableColumnFiledMap.connect]: undefined,
    [TableColumnFiledMap.isAble]: 1,
    [TableColumnFiledMap.connectCustoemr]: undefined,
    [TableColumnFiledMap.status]: 1,
    [TableColumnFiledMap.openCheckStock]: 'Y',
    [TableColumnFiledMap.openQuota]: 'Y',
    // [TableColumnFiledMap.allowEditStock]: 'N',
    belongAreaName: undefined,
    brandName: undefined,
    businessPersonName: undefined,
    areaList: [],
    // concatList: [],
    partnerAgent: []
}


export const BrandInfoEditTable = (props: {
    type?: "编辑"
    agentCode?: string
    history: any
    setData?: any[]
    getData: (data) => void
}) => {

    const [tableData, setTableData] = useState([{ ...defaultTableDataItem }])
    //品牌列
    const [brandList, setBrandList] = useState([])
    //是否加载
    // const [isLoading, setIsLoading] = useState(false)
    // 请求主考核客户
    const [querying, setQuerying] = useState(false)

    useEffect(() => {
        // setIsLoading(true)
        http.get(apis.BrandCompanySelectList).then(res => {
            setBrandList(res.data?.map(item => ({ code: item?.brandCode, name: item?.brandInfoName })))
            // setIsLoading(false)
        })
    }, [])

    useEffect(() => {
        // setIsLoading(true)
        if (props.setData) {
            const newTableData: any = JSON.parse(JSON.stringify(props.setData))
            let list = newTableData.map((item, index) => {
                item.areaList = [{ name: item.belongAreaName, code: item.belongAreaCode }]
                // item.concatList = [{ name: item.businessPersonName, code: item.businessPerson }]
                // item.concatList = []
                item.partnerAgent = item.partnerAgentCode && [{ name: item.partnerAgentName, code: item.partnerAgentCode }]
                item.isAble = item?.partnerAgentCode ? 0 : 1
                item.partnerAgentCode = item.partnerAgentCode || undefined
                return item
            })
            setTableData(list)
        }
    }, [props.setData])

    //关联主考核客户搜索
    const handleSearch = (val, index) => {
        if (val) {
            setQuerying(true)
            http.get(apis.ManyAgentMessage, { params: { agentName: val } }).then(res => {
                let data = res?.data?.agent || []
                handChange(data.map(item => ({ code: item.agentCode, name: item.agentName })), "partnerAgent", index)
            }).finally(() => setQuerying(false))
        }
    }

    //表格项编辑
    const handChange = (val, dataIndex, index) => {
        const newTableData: any = [ ...tableData ]
        if (typeof dataIndex === "string") {
            newTableData[index][dataIndex] = val
        } else {
            dataIndex.forEach((item, i) => {
                newTableData[index][item] = val[i]
            })
        }

        setTableData(newTableData)
    }

    const handleChangeTableData = (k: string, v: any, i: number) => {
      const data: any = [ ...tableData ]
      data[i][k] = v

      setTableData(data)
    }

    //提交表格
    const hendleSubmit = () => {
        const brands = []
        const data = tableData.map((item: any) => {
            if (!item[TableColumnFiledMap.brandName]) {
                message.error("请补全全部所属品牌后再提交表格！")
                return false
            } else if (brands.indexOf(item[TableColumnFiledMap.brandName]) !== -1) {
                message.error("所属品牌重复，请效验表格数据后再提交！")
                return false
            } else if (!item[TableColumnFiledMap.area]) {
                message.error(`请补全管理区域后再提交表格！`)
                return false
            }
            // else if (!item[TableColumnFiledMap.connect]) {
            //     message.error(`请补全关联业务员后再提交表格！`)
            //     return false
            // }
            else if (item[TableColumnFiledMap.isAble] === 0 && !item[TableColumnFiledMap.connectCustoemr]) {
                message.error(`请补全关联主考核客户后再提交表格！`)
                return false
            } else {
                brands.push(item[TableColumnFiledMap.brandName])
                let newItem: any = { ...item }
                if (props.type === "编辑" && !item?.id) {
                    newItem.agentCode = props.agentCode
                }
                if (newItem[TableColumnFiledMap.isAble] === 1) {
                    // 不是一户多开，主考核客户置空处理
                    newItem[TableColumnFiledMap.connectCustoemr] = null
                    delete newItem.partnerAgentName
                }
                delete newItem.areaList
                // delete newItem.concatList
                delete newItem.partnerAgent
                delete newItem[TableColumnFiledMap.isAble]

                return newItem
            }
        })
        props.getData && props.getData(data)

    }

    //添加|移除所属品牌信息
    const handleEditTableItem = (type: "add" | "remove", index?: number) => {
        if (type === "add") {
            setTableData([...tableData, { ...defaultTableDataItem }])
        } else if (type === "remove") {
            if (tableData.length === 1) {
                message.error("至少保留一项品牌信息！")
                return
            }
            index = index || 0
            setTableData(tableData.reduce((pre, cur, i) => {
                if (i === index) {
                    return [...pre]
                }
                return [...pre, cur]
            }, []))
        }
    }
    let style = {width:'160px'}
    return (
      <div className="brand-info-edit-table-box">
        <Button
          onClick={() => {
            handleEditTableItem('add')
          }}
          type="link"
        >
          添加所属品牌信息
        </Button>
        <Table
          // loading={isLoading}
          pagination={false}
          rowKey={(record, index) => index + ''}
          dataSource={tableData}
          columns={[
            {
              dataIndex: 'no',
              title: '序号',
              width: 50,
              render: (text, record, index) => index + 1,
            },
            {
              dataIndex: TableColumnFiledMap.brandName,
              title: '所属品牌',
              width: 160,
              render: (text, record: any, index) => (
                <Select
                  style={style}
                  disabled={record.id ? true : false}
                  value={record[TableColumnFiledMap.brandName]}
                  onChange={(val, option) => {
                    handChange(
                      [val, undefined, option.props.children, undefined, [], []],
                      [
                        TableColumnFiledMap.brandName,
                        TableColumnFiledMap.area,
                        'brandName',
                        TableColumnFiledMap.connect,
                        'areaList',
                      ],
                      index
                    )
                  }}
                  placeholder="请选择所属品牌"
                >
                  {brandList.map((item, index) => (
                    <Select.Option style={style} key={index} value={item.code}>
                      {item.name}
                    </Select.Option>
                  ))}
                </Select>
              ),
            },
            {
              dataIndex: TableColumnFiledMap.area,
              title: '管理区域',
              width: 150,
              render: (text, record, index) => (
                <TreeSelectInTable
                  disabled={!uaaApp.canUse(brandInformationEditAuth)}
                  val={record[TableColumnFiledMap.area]}
                  setVal={(val, label, list) => {
                    handChange([val, label[0], list], [TableColumnFiledMap.area, 'belongAreaName', 'areaList'], index)
                  }}
                  brandCode={record[TableColumnFiledMap.brandName]}
                  defaultDataList={record.areaList ? record.areaList : []}
                />
              ),
            },
            {
              dataIndex: TableColumnFiledMap.connect,
              title: '关联业务员',
              width: 180,
              render: (text, record, index) => {
                return (
                  <SelectInTable
                    list={record[TableColumnFiledMap.connect] || []}
                    val={
                      record[TableColumnFiledMap.connect]
                        ? record[TableColumnFiledMap.connect].map((a: any) => a.salesmanId)
                        : []
                    }
                    areaCode={record[TableColumnFiledMap.area]}
                    brandCode={record.brandCode}
                    disabled={!uaaApp.canUse(salesmanEditAuth)}
                    delVal={(val: any) => {
                      handleChangeTableData(
                        TableColumnFiledMap.connect,
                        record[TableColumnFiledMap.connect].filter(i => {
                          return i.salesmanId !== val
                        }),
                        index
                      )
                    }}
                    setVal={(list: any[]) => {
                      handleChangeTableData(TableColumnFiledMap.connect, list, index)
                      // handChange([null, null, list], [TableColumnFiledMap.connect, "businessPersonName", "concatList"], index)
                    }}
                  />
                )
              },
            },
            {
              dataIndex: TableColumnFiledMap.isAble,
              title: '是否支持一户多开',
              width: 130,
              render: (text, record, index) => {
                if (!uaaApp.canUse(brandInformationEditAuth)) {
                  // 没有权限编辑一户多开时，直接显示文本
                  return text == 0 ? '是' : '否'
                }
                return (
                  <Select
                    disabled={!uaaApp.canUse(brandInformationEditAuth)}
                    value={record[TableColumnFiledMap.isAble]}
                    onChange={val => {
                      handChange(val, TableColumnFiledMap.isAble, index)
                    }}
                    placeholder="请选择是否支持一户多开"
                  >
                    <Select.Option value={0}>是</Select.Option>
                    <Select.Option value={1}>否</Select.Option>
                  </Select>
                )
              },
            },
            {
              dataIndex: TableColumnFiledMap.connectCustoemr,
              title: '关联主考核客户',
              width: 190,
              render: (rext, record, index) => {
                return record[TableColumnFiledMap.isAble] === 0 ? (
                  <Select
                    disabled={!uaaApp.canUse(brandInformationEditAuth)}
                    value={record[TableColumnFiledMap.connectCustoemr]}
                    onChange={val => {
                      handChange(val, TableColumnFiledMap.connectCustoemr, index)
                    }}
                    placeholder="请输入客户名称搜索"
                    showSearch
                    defaultActiveFirstOption={false}
                    showArrow={false}
                    optionFilterProp="children"
                    onSearch={val => {
                      if (val) {
                        handleSearch(val, index)
                      }
                    }}
                    notFoundContent={querying ? <Spin size="small" /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                  >
                    {record.partnerAgent?.map((item, index) => (
                      <Select.Option key={index} value={item.code}>
                        {item.name}
                      </Select.Option>
                    ))}
                  </Select>
                ) : (
                  <></>
                )
              },
            },
            {
              dataIndex: TableColumnFiledMap.status,
              title: '状态',
              width: 80,
              render: (text, record, index) => {
                return (
                  <Switch
                    disabled={!uaaApp.canUse(brandInformationEditAuth)}
                    checked={record[TableColumnFiledMap.status] === 1}
                    onChange={val => {
                      let isValid = val ? 1 : 0
                      handChange(isValid, TableColumnFiledMap.status, index)
                    }}
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                  ></Switch>
                )
              },
            },
            {
              dataIndex: TableColumnFiledMap.openCheckStock,
              title: '盘点权限',
              width: 80,
              render: (text, record, index) => {
                return (
                  <Switch
                    disabled={!uaaApp.canUse(brandInformationEditAuth)}
                    checked={
                      record[TableColumnFiledMap.openCheckStock] === 'Y' ||
                      record[TableColumnFiledMap.openCheckStock] === null
                    }
                    onChange={val => {
                      let openCheckStock = val ? 'Y' : 'N'
                      handChange(openCheckStock, TableColumnFiledMap.openCheckStock, index)
                    }}
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                  ></Switch>
                )
              },
            },
            {
              dataIndex: TableColumnFiledMap.openQuota,
              title: '配额申请权限',
              width: 100,
              render: (text, record, index) => {
                return (
                  <Switch
                    disabled={!uaaApp.canUse(brandInformationEditAuth)}
                    checked={
                      record[TableColumnFiledMap.openQuota] === 'Y' || record[TableColumnFiledMap.openQuota] === null
                    }
                    onChange={val => {
                      let openQuota = val ? 'Y' : 'N'
                      handChange(openQuota, TableColumnFiledMap.openQuota, index)
                    }}
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                  ></Switch>
                )
              },
            },
            {
              dataIndex: TableColumnFiledMap.allowEditStock,
              title: '期初库存、期间开单数编辑权限',
              width: 200,
              render: (text, record, index) => {
                return (
                  <Switch
                    disabled={!uaaApp.canUse(brandInformationEditAuth)}
                    checked={record[TableColumnFiledMap.allowEditStock] === 'Y'}
                    onChange={val => {
                      let allowEditStock = val ? 'Y' : 'N'
                      handChange(allowEditStock, TableColumnFiledMap.allowEditStock, index)
                    }}
                    checkedChildren="启用"
                    unCheckedChildren="禁用"
                  ></Switch>
                )
              },
            },
            {
              dataIndex: 'do',
              title: '操作',
              width: 60,
              render: (text, record: any, index) =>
                !record.id ? (
                  <a
                    onClick={() => {
                      handleEditTableItem('remove', index)
                    }}
                    type="link"
                  >
                    移除
                  </a>
                ) : (
                  ''
                ),
            },
          ]}
        />
        <Affix offsetBottom={20} className="add-custom-ft" target={() => udConfigProvider.ui.getPageContainer()}>
          <div className="btn-box">
            <Button type="primary" onClick={hendleSubmit}>
              确定
            </Button>
            <Button
              onClick={() => {
                Modal.confirm({
                  title: '取消新增',
                  content: '取消后当前表单不会被保存，确认取消吗？',
                  okType: 'danger',
                  onOk: () => {
                    props.history.goBack()
                  },
                })
              }}
            >
              取消
            </Button>
          </div>
        </Affix>
      </div>
    )
}